package com.superhero.lock.util.tool;

import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import javax.annotation.Resource;
import java.util.function.Consumer;

/**
 *事务帮助类
 *
 *@author weijianxun
 *@date 2022/10/21 12:44
 */
@Component
public class TransactionUtil {
    @Resource
    private TaskExecutor transactionHelpThreadPool;

    /**
     * 如果当前存在事务则事务提交成功后执行，反之直接执行
     * @param consumer
     */
    public void afterCommitOrCommitNow(Consumer consumer) {
        try {
            if (TransactionSynchronizationManager.isActualTransactionActive()) {
                TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
                    @Override
                    public void afterCommit() {
                        consumer.accept(null);
                    }
                });
            } else {
                consumer.accept(null);
            }
        } catch (Exception e) {
            // todo log error
        }
    }

    /**
     * 异步： 如果当前存在事务则事务提交成功后执行，反之直接执行
     * @param consumer
     */
    public void afterCommitOrCommitNowAsync(Consumer consumer) {
        try {
            if (TransactionSynchronizationManager.isActualTransactionActive()) {
                TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
                    @Override
                    public void afterCommit() {
                        transactionHelpThreadPool.execute(() -> {
                            consumer.accept(null);
                        });
                    }
                });
            } else {
                transactionHelpThreadPool.execute(() -> {
                    consumer.accept(null);
                });
            }
        } catch (Exception e) {
            // todo log error
        }
    }
}
